/*********************************************************
 *
 * Filename: misc/led/cm_led.c
 *   Author: jmdvirus
 *   Create: 2019年01月02日 星期三 19时57分24秒
 *
 *********************************************************/

#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "cm_led.h"
#include "cm_utils.h"
#include "rt_print.h"

typedef struct
{
    char   dev[512];
    char   cmd_on[576];
    char   cmd_off[576];
} LedNormalPriv;

static int cm_led_normal_open(struct CMLedContext* ctx, const char *dev)
{
    if (!ctx || !dev)
        return -1;
    LedNormalPriv *priv = (LedNormalPriv*)malloc(sizeof(LedNormalPriv));
    assert(priv != NULL);
    ctx->priv_data = priv;

    cm_strncpy(priv->dev, dev, sizeof(priv->dev));
    sprintf(priv->cmd_on, "echo 1 > %s", priv->dev);
    sprintf(priv->cmd_off, "echo 0 > %s", priv->dev);
#if 0
	lc->fd = fopen(lc->szDev, "w");
	if (lc->fd < 0) {
		return -2;
	}
#endif
    return 0;
}

static int cm_led_normal_close(struct CMLedContext* ctx)
{
    if (!ctx)
        return -1;
    if (ctx->priv_data)
    {
        free(ctx->priv_data);
    }
#if 0
	if (lc->fd) {
		fclose(lc->fd);
	}
#endif

    return 0;
}

static int cm_led_normal_on(struct CMLedContext* ctx)
{
    if (!ctx || !ctx->priv_data)
        return -1;
    LedNormalPriv  *p = (LedNormalPriv *)ctx->priv_data;
    rtdebug("led ctrl set normal on of device [%s]\n", p->dev);
    int ret = 0;
#if 0
	int ret = fwrite("1", 1, 1, lc->fd);
#else
    // int ret = cm_write_file_data(lc->szDev, "1", 1);
    system(p->cmd_on);
#endif
    return ret;
}

static int cm_led_normal_off(struct CMLedContext* ctx)
{
    if (!ctx || !ctx->priv_data)
        return -2;
    LedNormalPriv  *p = (LedNormalPriv *)ctx->priv_data;
    rtdebug("led ctrl set normal off of device [%s]\n", p->dev);
    int ret = 0;
#if 0
	int ret = fwrite("0", 1, 1, lc->fd);
#else
    // int ret = cm_write_file_data(lc->szDev, "0", 1);
    system(p->cmd_off);
#endif
    return ret;
}

static int cm_led_normal_blink(struct CMLedContext* ctx, int on_duration, int off_duration)
{
    if (!ctx || !ctx->priv_data)
        return -1;

    return 0;
}

const CMLedImpl cm_led_impl_normal = {
    .name = "led_normal",
    .open = cm_led_normal_open,
    .close = cm_led_normal_close,
    .on = cm_led_normal_on,
    .off = cm_led_normal_off,
    .blink = cm_led_normal_blink,
};
